package com.juc.threadlocal;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author Zan
 * @Create 2024/5/12 12:27
 * @ClassName : ThreadLocalDemo
 * @Description :
 *
 *      需求1：5个销售卖房子，集团高层只关心销售总量的准确统计数，按照总销售额统计，方便集团公司做计划统计，给部分发送奖金
 *
 *      需求2：5个销售卖完随机数的房子后，各自独立销售额度，按照自己的业绩按提成走，分灶吃饭，各个营销自己动手，丰衣足食
 */

class House {

    int saleCount = 0;

    public synchronized void saleHouse() { // ①
        saleCount++;
    }

    /*ThreadLocal<Integer> saleVolume = new ThreadLocal<Integer>() { // 现在都不用这个匿名内部类的方法来写，太麻烦了，都用withInitial()方法来初始化
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };*/

    ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(() -> 0);

    public void saleHouseByThreadLocal() {
        saleVolume.set(saleVolume.get() + 1);
    }
}

public class ThreadLocalDemo {
    public static void main(String[] args) {
        House house = new House();

        for (int i = 1; i <= 5; i++) {
            new Thread(() -> {
                int size = new Random().nextInt(5) + 1;
                try {
                    for (int j = 1; j <= size; j++) {
                        house.saleHouse();
                        house.saleHouseByThreadLocal();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t 号销售卖出：" + house.saleVolume.get() + " 套房子");
                } finally {
                    house.saleVolume.remove();
                }
            }, String.valueOf(i)).start();
        }

        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "\t 共计卖出多少套：" + house.saleCount);
    }
}
